package com.project.market.service.impl;

import com.github.pagehelper.PageHelper;
import com.project.market.db.domain.MarketOrder;
import com.project.market.db.domain.MarketOrderExample;
import com.project.market.db.domain.MarketOrderGoods;
import com.project.market.db.domain.MarketOrderGoodsExample;
import com.project.market.db.mapper.MarketOrderGoodsMapper;
import com.project.market.db.mapper.MarketOrderMapper;
import com.project.market.db.mapper.MarketSystemMapper;
import com.project.market.service.AdminOrderService;
import com.project.market.util.MybatisUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import sun.util.resources.cldr.to.TimeZoneNames_to;

import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class AdminOrderServiceImpl implements AdminOrderService {
    @Override
    public List<MarketOrder> list(String page, String limit, String sort, String order, String start, String end, String userId, String orderSn, String orderStatusArray) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        SqlSession session = MybatisUtil.getSession();
        MarketOrderMapper OrderMapper = session.getMapper(MarketOrderMapper.class);

        MarketOrderExample OrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = OrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));

        try {
            if (userId != null && !"".equals(userId)) {
                criteria.andUserIdEqualTo(Integer.valueOf(userId));
            }
            if (orderSn != null && !"".equals(orderSn)) {
                criteria.andOrderSnEqualTo(orderSn);
            }
            if (orderStatusArray != null && !"".equals(orderStatusArray)) {
                criteria.andOrderStatusEqualTo(Short.valueOf(orderStatusArray));
            }

            if (!("".equals(start) || "".equals(end))) {
                criteria.andPayTimeBetween(LocalDateTime.parse(start, df), LocalDateTime.parse(end, df));
            }
        } catch (Exception e) {
            return null;
        }
        OrderExample.setOrderByClause(sort + " " + order);

        List<MarketOrder> list = OrderMapper.selectByExample(OrderExample);


        session.commit();
        session.close();

        return list;
    }

    @Override
    public Map<String, Object> detail(String id) {
        SqlSession session = MybatisUtil.getSession();
        MarketOrderMapper orderMapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        try {
            criteria.andIdEqualTo(Integer.valueOf(id));
        } catch (Exception e) {
            return null;
        }

        MarketOrder marketOrder = orderMapper.selectOneByExample(marketOrderExample);

        MarketOrderGoodsMapper orderGoodsMapper = session.getMapper(MarketOrderGoodsMapper.class);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria1 = marketOrderGoodsExample.createCriteria();
        criteria1.andDeletedEqualTo(false);
        criteria1.andOrderIdEqualTo(Integer.valueOf(id));

        List<MarketOrderGoods> goods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);


        HashMap<String, Object> map = new HashMap<>();

        map.put("orderGoods", goods);
        map.put("order", marketOrder);

        session.commit();
        session.close();
        return map;
    }

    @Override
    public Integer delete(Integer id) {
        SqlSession session = MybatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(id);
        MarketOrder marketOrder = mapper.selectOneByExample(marketOrderExample);
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(LocalDateTime.now());
        Integer index = mapper.updateByExample(marketOrder, marketOrderExample);
        session.commit();
        session.close();
        return index;
    }

    /*
    发货，修改订单状态
     */
    @Override
    public Integer ship(Integer orderId, String shipChannel, String shipSn) {
        SqlSession session = MybatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(orderId);

        MarketOrder marketOrder = mapper.selectByPrimaryKey(orderId);
        marketOrder.setShipChannel(shipChannel);
        marketOrder.setShipSn(shipSn);
        marketOrder.setOrderStatus((short) 301);

        Integer index = mapper.updateByExample(marketOrder, marketOrderExample);


        session.commit();
        session.close();

        return index;
    }

    @Override
    public List<Object> channel() {

        List<Object> list = new ArrayList<>();

        try {

            File file = new File(AdminOrderServiceImpl.class.getResource("/shipChannel.txt").getFile());


            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");

            BufferedReader bufferedReader = new BufferedReader(isr);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                Map<String, Object> map = new HashMap<>();
                String code = line.substring(0, line.indexOf("="));
                map.put("code", code);
                map.put("name", line.replace(code + "=", ""));
                list.add(map);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return list;
    }

    @Override
    public Integer refund(Integer orderId, String refundMoney) {
        SqlSession session = MybatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);


        criteria.andIdEqualTo(orderId);

        MarketOrder marketOrder = mapper.selectByPrimaryKey(orderId);
        marketOrder.setRefundAmount(new BigDecimal(refundMoney));
        marketOrder.setOrderStatus((short) 203);
        marketOrder.setUpdateTime(LocalDateTime.now());

        Integer index = mapper.updateByExample(marketOrder, marketOrderExample);


        session.commit();
        session.close();

        return index;


    }
}
